import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { debounce } from '@/utils/index'
axios.defaults.headers = {
  'Content-Type': 'application/json;charset=UTF-8'
}
// axios.defaults.transformRequest = [function(data) {
//         var newData = "";
//         for (var k in data) {
//             newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
//         }
//         return newData
//     }]
// create an axios instance
const service = axios.create({
  baseURL: '', // process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
const loginToken = token => {
  return 'Basic dGVzdF9jbGllbnQ6dGVzdF9zZWNyZXQ='
}
const formatToken = token => {
  return `Bearer ${token}`
}
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log('config', config)
    const isSearchFn = localStorage.getItem('isSearchFn')

    if (isSearchFn && config.params && config.params.current) {
      delete config.params.current
      localStorage.removeItem('isSearchFn')
    }
    if (config.data) {
      delete config.data.createdTime
      delete config.data.updateTime
    }
    if (config.method == 'post') {}
    if (store.getters.token) {
      console.log(store.getters.token)
      // let each request carry token --['X-Token'] as a custom key.
      // please modify it according to the actual situation.
      // config.headers['X-Token'] = getToken()
      config.headers.Authorization = formatToken(store.getters.token)
    } else {
      config.headers.Authorization = loginToken()
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error, '++++error+++') // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
     * If you want to get information such as headers or status
     * Please return  response => response
     */

  /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code.
     */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '000000' && !res.access_token && res.code !== '040005') {
      debounce(Message({
        message: res.mesg || 'error',
        type: 'error',
        duration: 5 * 1000
      }), 3000)

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('登录失效', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(res.mesg || 'error')
    } else {
      if ((res.code = '000000' && res.data == true)) {
        Message({
          message: res.mesg,
          type: 'success',
          duration: 2 * 1000
        })
      } else {
        console.log(res, '++++res++++')
        return res
      }
    }
  },
  error => {
    console.log('err:' + error) // for debug
    // debounce(Message({
    //     message: res.mesg || "error",
    //     type: "error",
    //     duration: 5 * 1000
    // }), 3000)
    return Promise.reject(error)
  }
)

export default service
